<?php

class Tools extends GXClass {

	private $GXCookie;

	/**
	 * __construct
	 *
	 * Loads the User and Cookie modules.
	 */
	public function __construct(){
		parent::__construct();
		$this->GXCookie = GXCookie::getInstance();
		$this->user = $this->GXPage->User;
		return true;
	}

	public function userAgent(){
		// grab the user agent object
		$ua = $this->GXPage->Run->UserAgent;
		// grab the platform-already-processed cookie
		$platform = $this->GXCookie->get('GXPage-Platform');
		// default force
		$force = false;

		// if $home is already set, make sure we're in the right place
		switch($platform){
			case 'i':
				// make sure we're within page @ID = 'iPhone'
				$page = $this->GXPage->Params->Page;
				$sys = $this->GXPage->get('SiteConfig')->getConfig();
				$exists = $sys->exec->xpath('//*[ @ID = "' .$page .'" ]/ancestor-or-self::Page[ @ID = "iPhone" ]');
				if(!$exists){
					$force = true;
				}
				break;
			default:
				trigger_error('Standard desktop browser; let it pass', E_USER_WARNING);
				$force = false;
		}

		// if we do not have a platform or we're forced to run this again
		if(!$platform || $force){
			// handle supported platforms
			switch(true){
				// mobile webkit
				case is_numeric(strpos(strtolower($ua->Browser->name), 'safari')) && is_numeric(strpos(strtolower($ua->Platform->name), 'mobile')):
					trigger_error('We have Mobile WebKit, setting Page to i', E_USER_WARNING);
					$this->GXPage->Params->Page = 'i';
					$this->GXPage->Params->Action = null;
					$this->GXCookie->set('GXPage-Platform', 'i');
					header('Location: ' .$this->GXPage->Layout->Client->BaseHREF .'iPhone');
					exit();
					break;
				// probably desktop
				default:
					trigger_error('--------- We have a standard desktop browser (' .$ua->Browser->name .' running on ' .$ua->Platform->name .')', E_USER_ERROR);
			}
		}
		return true;
	}

	/**
	 * getCountries
	 *
	 * Returns a list of countries.
	 * @param string $val the selected value
	 * @return object GXDOM or false on failure
	 */
	public function getCountries( $val = null ){
		// default to US
		if( !$val ){
			$val = 'US';
		}
		// start the return object
		$r = new GXDOM('FieldOptions',null,array('As'=>'select'));
		// get the list
		$c = $this->countrydb->exec->xpath( '/*[1]/c' );
		// the database is hierarchical, so build each node ... we only want the country, not the states inside
		foreach( $c as $country ){
			$node = array(
				'Label'	=> $country->attributes['label'],
				'Value'	=> $country->attributes['id']
				);
			// set the selected value to the provided option
			if( $country->attributes['id'] == $val ){
				$node['default'] = '1';
			}
			$r->c( $node );
		}
		return $r;
	}

	/**
	 * getStates
	 *
	 * Returns a list of states based on the provided country code.
	 * @param string $code the 2-letter code of the country
	 * @return object GXDOM or false on failure
	 */
	public function getStates( $code = null, $root = 'value' ){
		// default to US
		if( !$code ){
			$code = 'US';
		}
		// load the countries database
		$countrydb = new GXDOM( $this->GXPage->Layout->FS->GXPage .'Data/countries.xml' );
		// start the return object
		$r = new GXDOM($root,null,array('groupid'=>$code));
		// get the country
		$c = $countrydb->exec->xpath( '//c[ @id = "' .$code .'" ]//sp' );
		if( !$c ){
			trigger_error( 'Unable to find a country with that code (' .$code .')', E_USER_ERROR );
			$r->option( null, array('label'=>'Not required','value'=>'') );
			return $r;
		}
		// add a "please select" as the first option so that when switching countries, we don't save an invalid location
		$state = new GXDOM('option',null,array('value'=>'0','label'=>'-- Select one --'));
		$r->foo( $state->node, GXDOM::NO_CONTAINER );
		// we might have regions with state within or just a list of states
		// so pass in the DOM node, not the GXDOM object
		foreach( $c as $state ){
			$atts = array(
				'label'	=> $state->attributes['label'],
				'value'	=> $state->attributes['id']
				);
			if( isset($state->attributes['default']) ){
				$atts['default'] = 1;
			}
			$r->option( null, $atts );
		}
		return $r;
	}

	public function generateSitemap(){
		$baseurl = 'http://www.potdaq.com/';
		$atts = array(
			'xmlns'		=> 'http://www.google.com/schemas/sitemap/0.84',
			'xmlns:xsi'	=> 'http://www.w3.org/2001/XMLSchema-instance',
			'xsi:schemaLocation'	=> 'http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd'
			);
		$map = new GXDOM('urlset', null, $atts);

		// add collectives at the top
		$sql = 'SELECT * FROM service_info WHERE status <> \'UNLISTED\' ORDER BY name ASC';
		$dlist = $this->db->get($sql);
		if( !$dlist ){
			trigger_error('Something\'s wrong ... no services', E_USER_ERROR);
		}
		if( count($dlist) ){
			foreach($dlist as $d){
				if( !$d->handle ){
					continue;
				}
				$p = $map->url();
				$p->loc($baseurl .$d->handle);
				$p->priority('1.0');
				$mod = array_shift(split('\.', $d->modified));
				$p->lastmod(date('c', strtotime($mod)));
				$p->changefreq('weekly');
			}
		}

		// add news articles
		$sql = 'SELECT * FROM article_info ORDER BY modified DESC';
		$alist = $this->db->get($sql);
		if( !$alist ){
			trigger_error('Unable to get articles', E_USER_ERROR);
		}
		if( count($alist) ){
			foreach($alist as $a){
				if( !$a->handle ){
					continue;
				}
				$p = $map->url();
				$p->loc($baseurl .$a->handle);
				$p->priority('1.0');
				$mod = array_shift(split('\.', $a->modified));
				$p->lastmod(date('c', strtotime($mod)));
				$p->changefreq('weekly');
			}
		}

		// generate map
		$site = $this->GXPage->SiteConfig->getConfig();
		// get all visible, non-member pages
		$pages = $site->exec->xpath('/Pages/Page[ not(@Visible = \'0\') and (Auth/Role/@ID = \'GUEST\') ]');
		foreach( $pages as $conf ){
			$conf = simplexml_import_dom($conf->node);
			$p = $map->url();
			$p->loc('http://www.potdaq.com/' .$conf['ID']);
			$p->priority('0.5');
			$file = stat($this->GXPage->Layout->FS->Pages .strval($conf->File));
			$p->lastmod(date('c', $file['mtime']));
			$p->changefreq('weekly');
		}
		return $map;
	}

	/**
	 * getRandomString
	 * Generates a random string of the specified length.
	 * @return string
	 */
	public function getRandomString($len = 5){
		$i = 0;
		$str = null;
		$doc = null;
		// create an n-character random string
		for( $i = 0; $i < $len; $i++ ){
			$str .= chr(rand(65,90));
		}
		// use lower case, since it's easier to read
		return strtolower($str);
	}

}
?>